import 'dart:math';
import 'dart:ui';

import 'package:chatgreat/bloc/chat_chat_bloc.dart';
import 'package:chatgreat/bloc/free_count_bloc.dart';
import 'package:chatgreat/helper/AppUtil.dart';
import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/color.dart';
import 'package:chatgreat/helper/global_store.dart';
import 'package:chatgreat/helper/haptic_feedback.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/cache.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/chat/component/model_switcher.dart';
import 'package:chatgreat/page/chat/room_chat.dart';
import 'package:chatgreat/page/component/audio_player.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/button.dart';
import 'package:chatgreat/page/component/chat/chat_preview.dart';
import 'package:chatgreat/page/component/chat/empty.dart';
import 'package:chatgreat/page/component/chat/file_upload.dart';
import 'package:chatgreat/page/component/chat/voice_record.dart';
import 'package:chatgreat/page/component/global_alert.dart';
import 'package:chatgreat/page/component/model_indicator.dart';
import 'package:chatgreat/page/component/notify_message.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api/model.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/model/chat_history.dart';
import 'package:chatgreat/repo/model/chat_question.dart';
import 'package:chatgreat/repo/model/misc.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:custom_sliding_segmented_control/custom_sliding_segmented_control.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:go_router/go_router.dart';
import 'package:in_app_review/in_app_review.dart';
import 'package:markdown_widget/config/all.dart';
import 'package:notification_center/notification_center.dart';
import 'package:quickalert/models/quickalert_type.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../bloc/chat_message_bloc.dart';
import '../../bloc/notify_bloc.dart';
import '../../bloc/room_bloc.dart';
import '../../helper/constant.dart';
import '../../helper/event.dart';
import '../../helper/logger.dart';
import '../../helper/my_widget.dart';
import '../../repo/model/message.dart';
import '../../widgets/flutter_life_state/src/base_life_state.dart';
import '../component/chat/chat_input.dart';
import '../component/chat/help_tips.dart';
import '../component/chat/message_state_manager.dart';
import '../component/enhanced_error.dart';
import 'component/stop_button.dart';

class HomePage extends StatefulWidget {
  /// 聊天内容窗口状态管理器
  final MessageStateManager stateManager;
  final SettingRepository setting;
  final bool showInitialDialog;
  final int? reward;
  const HomePage({
    super.key,
    required this.stateManager,
    required this.setting,
    this.showInitialDialog = false,
    this.reward,
  });

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends BaseLifeState<HomePage> {
  // 聊天内容界面控制器
  final ChatPreviewController chatPreviewController = ChatPreviewController();
  // 聊天内容滚动控制器
  final ScrollController scrollController = ScrollController();
  // 输入框是否可编辑
  final ValueNotifier<bool> enableInput = ValueNotifier(true);
  // 音频播放器控制器
  final AudioPlayerController audioPlayerController =
      AudioPlayerController(useRemoteAPI: true);
  // 主页ID
  int chatId = 9527;

  ModelIndicator? currentModel;
  List<HomeModelV2> models = [
    HomeModelV2(
      modelId: "gpt-3.5-turbo",
      modelName: 'Chat-3.5',
      type: 'model',
      id: 'pt-3.5-turbo',
      supportVision: false,
      name: 'Chat3.5',
    ),
    HomeModelV2(
      modelId: "gpt-5",
      modelName: 'Chat5',
      type: 'model',
      id: 'openai:gpt-5',
      supportVision: false,
      name: 'Chat4o',
    ),
  ];

  /// 是否显示提示消息对话框
  bool showFreeModelNotifyMessage = false;

  List<FileUpload> selectedImageFiles = [];

  /// chux事件
  PromotionEvent? promotionEvent;

  /// Maximum height of the chat input box
  int inputMaxLines = 6;

  bool isFirst = true;

  final GlobalKey<ChatPreviewState> _previewPageKey = GlobalKey();
  final GlobalKey<ChatInputState> _inputViewKey = GlobalKey();

  @override
  void didChangeDependencies() {
    precacheImage(const AssetImage("assets/Chat3.5.png"), context);
    precacheImage(const AssetImage("images/Chat5.0.png"), context);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    audioPlayerController.dispose();
    chatPreviewController.dispose();
    NotificationCenter().unsubscribe(HOME_ALERT_VIP_NOTIF);
    GlobalEvent().off('refresh_0');
    super.dispose();
  }

  @override
  void initState() {
    context.read<ChatChatBloc>().add(ChatChatLoadRecentHistories());
    FlutterNativeSplash.remove();
    //请求能力，后期优化
    APIServer().capabilities().then((cap) {
      //更新能力
      Ability().updateCapabilities(cap);

      if (cap.homeModels.isNotEmpty) {
        models = cap.homeModels;

        if (mounted) {
          // 加载免费模型剩余使用次数
          if (currentModel != null && currentModel!.model.freeCount != null) {
            context.read<FreeCountBloc>().add(
                FreeCountReloadEvent(model: currentModel!.model.freeCount!));
          }
          setState(() {});
        }
      }
    });

    if (Ability().homeModels.isNotEmpty) {
      models = Ability().homeModels;
    }

    setState(() {
      currentModel = ModelIndicator(
        model: models[0],
        iconAndColor: iconAndColors[0],
      );
    });

    // 版本检查
    // APIServer().versionCheck().then((resp) {
    //   final lastVersion = widget.setting.get('last_server_version');
    //   if (resp.serverVersion == lastVersion && !resp.forceUpdate) {
    //     return;
    //   }
    //   if (resp.hasUpdate) {
    //     showBeautyDialog(
    //       context,
    //       type: QuickAlertType.success,
    //       text: resp.message,
    //       confirmBtnText: '去更新',
    //       onConfirmBtnTap: () {
    //         launchUrlString(resp.url, mode: LaunchMode.externalApplication);
    //       },
    //       cancelBtnText: '暂不更新',
    //       showCancelBtn: true,
    //     );
    //   }
    //   widget.setting.set('last_server_version', resp.serverVersion);
    // });
    // 加载当前聊天室信息
    context.read<RoomBloc>().add(RoomLoadEvent(
          chatHomeRoomId,
          chatHistoryId: chatId,
          cascading: true,
        ));
    // 查询最近聊天记录
    context
        .read<ChatMessageBloc>()
        .add(ChatMessageGetRecentEvent(chatHistoryId: chatId));

    chatPreviewController.addListener(() {
      setState(() {});
    });

    NotificationCenter().subscribe(HOME_ALERT_VIP_NOTIF, (p0) {
      if (mounted) {
        Future.delayed(const Duration(milliseconds: 500))
            .then((value) => _showVipDialog());
      }
    });

    GlobalEvent().on("refresh_0", (data) {
      if (mounted) {
        // 刷新聊天室信息
        context.read<RoomBloc>().add(RoomLoadEvent(
              chatHomeRoomId,
              chatHistoryId: chatId,
              cascading: true,
            ));
      }
    });

    super.initState();
  }

  @override
  void onResumed() {
    super.onResumed();
    if (isFirst) {
      isFirst = false;
      return;
    }

    // 加载免费模型剩余使用次数
    if (currentModel != null && currentModel!.model.freeCount != null) {
      context
          .read<FreeCountBloc>()
          .add(FreeCountReloadEvent(model: currentModel!.model.freeCount!));
    }
  }

  @override
  Widget build(BuildContext context) {
    var customColors = Theme.of(context).extension<CustomColors>()!;
    // AppUtil().touristLoginModel?.isVip = 1;

    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        padding: const EdgeInsets.only(top: 12),
        child: SafeArea(
            child: BlocBuilder<ChatChatBloc, ChatChatState>(
          buildWhen: (previous, current) =>
              current is ChatChatRecentHistoriesLoaded,
          builder: (context, state) {
            if (state is ChatChatRecentHistoriesLoaded) {
              return Column(
                children: [
                  SizedBox(
                    height: 118,
                    child: SliverSingleComponent(
                      expendedHeight: 80,
                      title: BlocBuilder<FreeCountBloc, FreeCountState>(
                        buildWhen: (previous, current) =>
                            current is FreeCountLoadedState,
                        builder: (context, state) {
                          if (state is FreeCountLoadedState) {
                            if (state.counts.isNotEmpty) {
                              var count = state.counts.first;
                              currentModel!.model.name = count.name;
                              currentModel!.model.freeCount =
                                  count.leftCount.toString();
                            }
                            if (currentModel != null &&
                                currentModel!.model.freeCount != null &&
                                ((AppUtil().touristLoginModel?.isVip ?? 0) ==
                                    0)) {
                              return Container(
                                margin: const EdgeInsets.only(bottom: 2),
                                padding: const EdgeInsets.only(
                                    left: 34, right: 34, top: 8, bottom: 8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  color: Colors.white.withOpacity(0.1),
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    const Text('您还有',
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 15)),
                                    Text(
                                      '${currentModel!.model.freeCount}',
                                      style: TextStyle(
                                        color: customColors.tabBarColor,
                                        fontSize: 16,
                                      ),
                                    ),
                                    const Text('次免费咨询次数',
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 15)),
                                  ],
                                ),
                              );
                            }
                          }
                          return const SizedBox();
                        },
                      ),
                      leading: IconButton(
                        icon: Image.asset('images/add.png'),
                        onPressed: () => _showClearDialog(),
                      ),
                      actions: [
                        IconButton(
                          icon: Image.asset('images/help.png'),
                          onPressed: () {
                            context.push('/home-help');
                          },
                        ),
                      ],
                      bottom: PreferredSize(
                        preferredSize: Size(ScreenUtil().screenWidth, 118),
                        child: buildTopComponents(customColors, context, state),
                      ),
                      appBarExtraWidgets: () {
                        return [];
                      },
                    ),
                  ),

                  Expanded(
                    child: BlocConsumer<RoomBloc, RoomState>(
                      listenWhen: (previous, current) =>
                          (current is RoomLoaded) &&
                          current.room.id == chatHomeRoomId,
                      listener: (context, state) async {
                        if (state is RoomLoaded && state.cascading) {
                          context.read<FreeCountBloc>().add(
                              FreeCountReloadEvent(
                                  model: currentModel!.model.freeCount ?? ''));
                        }
                      },
                      buildWhen: (previous, current) =>
                          (current is RoomLoaded) &&
                          current.room.id == chatHomeRoomId,
                      builder: (context, room) {
                        // 加载聊天室
                        if (room is RoomLoaded) {
                          if (room.error != null) {
                            return EnhancedErrorWidget(error: room.error);
                          }
                          return buildChatComponents(
                            customColors,
                            context,
                            room,
                          );
                        } else {
                          return Container();
                        }
                      },
                    ),
                  ),

                  // 聊天输入窗口
                  if (!chatPreviewController.selectMode)
                    Container(
                      decoration: const BoxDecoration(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(10),
                          topRight: Radius.circular(10),
                        ),
                        color: Colors.transparent,
                      ),
                      child: BlocBuilder<FreeCountBloc, FreeCountState>(
                        builder: (context, freeState) {
                          var hintText = '请输入你的问题~';
                          return BlocBuilder<ChatMessageBloc, ChatMessageState>(
                            buildWhen: (previous, current) =>
                                current is ChatMessagesLoaded,
                            builder: (context, state) {
                              return ChatInput(
                                key: _inputViewKey,
                                keyIndex: 1,
                                enableNotifier: enableInput,
                                enableImageUpload: false,
                                hintText: hintText,
                                onSubmit: (value) {
                                  handleSubmit(value);
                                  FocusManager.instance.primaryFocus?.unfocus();
                                },
                                onVoiceRecordTappedEvent: () {
                                  audioPlayerController.stop();
                                },
                                onAlertVipTappedEvent: () {
                                  _showVipDialog();
                                },
                                onStopGenerate: () {
                                  context
                                      .read<ChatMessageBloc>()
                                      .add(ChatMessageStopEvent());
                                },
                              );
                            },
                          );
                        },
                      ),
                    ),
                ],
              );
            } else {
              return const SizedBox();
            }
          },
        )),
      ),
    );
  }

  Map<String, ModelIndicator> buildModelIndicators() {
    Map<String, ModelIndicator> map = {};

    for (var i = 0; i < models.length; i++) {
      var model = models[i];
      map[model.id] = ModelIndicator(
        model: model,
        selected: model.id == currentModel?.model.id,
        // iconAndColor: iconAndColors[i],
        iconAndColor: null,
        itemCount: models.length,
      );
    }

    return map;
  }

  Container buildTopComponents(
    CustomColors customColors,
    BuildContext context,
    ChatChatRecentHistoriesLoaded state,
  ) {
    final indicators = buildModelIndicators();
    return Container(
      color: Colors.transparent,
      child: Stack(
        children: [
          Column(
            children: [
              if (Ability().showGlobalAlert) const GlobalAlert(pageKey: 'home'),
              // 首页通知消息组件
              // if (showFreeModelNotifyMessage && promotionEvent != null)
              //   buildNotifyMessageWidget(context),

              //模型选择
              // Visibility(
              //   visible: (AppUtil().touristLoginModel?.isVip ?? 0) == 0,
              //   // visible: false,
              //   child: Center(
              //     child: Container(
              //       width: 220.w,
              //       margin: const EdgeInsets.only(top: 6, bottom: 24),
              //       child: ClipRRect(
              //         borderRadius: BorderRadius.circular(13),
              //         child: CustomSlidingSegmentedControl<String>(
              //           children: indicators,
              //           padding: 0,
              //           isStretch: true,
              //           height: 40,
              //           innerPadding: const EdgeInsets.all(0),
              //           decoration: BoxDecoration(
              //             color: customColors.columnBlockBackgroundColor
              //                 ?.withOpacity(0.1),
              //           ),
              //           thumbDecoration: const BoxDecoration(
              //             gradient: LinearGradient(
              //               colors: [
              //                 Color(0xFF14E0EB),
              //                 Color(0xFF5988FC),
              //               ],
              //               begin: Alignment.centerLeft,
              //               end: Alignment.centerRight,
              //             ),
              //             // borderRadius: BorderRadius.circular(6),
              //           ),
              //           duration: const Duration(milliseconds: 300),
              //           curve: Curves.easeInToLinear,
              //           customSegmentSettings: CustomSegmentSettings(
              //             borderRadius: BorderRadius.circular(13),
              //           ),
              //           onTapSegment: (value) {
              //             if ((AppUtil().touristLoginModel?.isVip ?? 0) == 0) {
              //               _showVipDialog();
              //               return false;
              //             }
              //             return true;
              //           },
              //           onValueChanged: (value) {
              //             currentModel = indicators[value];
              //             // 重新读取模型的免费使用次数
              //             if (currentModel != null &&
              //                 currentModel!.model.freeCount != null) {
              //               context.read<FreeCountBloc>().add(
              //                   FreeCountReloadEvent(
              //                       model:
              //                           currentModel!.model.freeCount ?? ''));
              //             }
              //             setState(() {});
              //           },
              //         ),
              //       ),
              //     ),
              //   ),
              // ),
              if (currentModel != null && isNotBlank(currentModel!.model.name))
                Center(
                    child: Image.asset('images/Chat5.0.png'))
              else
                const SizedBox(height: 18, width: 220),

              Container(
                  margin: (AppUtil().touristLoginModel?.isVip ?? 0) == 0
                      ? const EdgeInsets.only(top: 4)
                      : const EdgeInsets.only(top: 4, bottom: 20),
                  alignment: Alignment.center,
                  child: Text(
                    '无所不知，问你想问',
                    style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.normal,
                        color: Colors.white.withOpacity(0.6)),
                  )),
            ],
          ),
          //语音
          Align(
            alignment: Alignment.centerRight,
            child: RepaintBoundary(
              child: Container(
                color: Colors.transparent,
                margin: const EdgeInsets.only(right: 8),
                child: IconButton(
                  iconSize: 32,
                  icon: Image.asset('images/speech.png'),
                  onPressed: () {
                    if (currentModel != null &&
                        currentModel!.model.freeCount != null) {
                      if ((AppUtil().touristLoginModel?.isVip ?? 0) == 0 &&
                          currentModel!.model.freeCount == '0') {
                        _showVipDialog();
                        return;
                      }
                    }

                    context.push('/home_speeh_chat', extra: {
                      'name': '语音对聊',
                      'avater': "",
                      'roomId': chatHomeRoomId
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  NotifyMessageWidget buildNotifyMessageWidget(BuildContext context) {
    return NotifyMessageWidget(
      title: promotionEvent!.title != null
          ? Text(
              promotionEvent!.title!,
              style: TextStyle(
                color: stringToColor(promotionEvent!.textColor ?? 'FFFFFFFF'),
                fontWeight: FontWeight.bold,
              ),
            )
          : null,
      backgroundImageUrl: promotionEvent!.backgroundImage,
      height: 85,
      closeable: promotionEvent!.closeable,
      onClose: () {
        setState(() {
          showFreeModelNotifyMessage = false;
        });

        Cache().setBool(
          key: 'show_home_free_model_message',
          value: false,
          duration: Duration(days: promotionEvent!.maxCloseDurationInDays ?? 7),
        );
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: Text(
              promotionEvent!.content,
              style: TextStyle(
                color: stringToColor(promotionEvent!.textColor ?? 'FFFFFFFF'),
                fontSize: 14,
                overflow: TextOverflow.ellipsis,
              ),
              maxLines: 2,
            ),
          ),
          if (promotionEvent!.clickButtonType !=
                  PromotionEventClickButtonType.none &&
              promotionEvent!.clickValue != null &&
              promotionEvent!.clickValue!.isNotEmpty)
            InkWell(
              onTap: () {
                switch (promotionEvent!.clickButtonType) {
                  case PromotionEventClickButtonType.url:
                    if (promotionEvent!.clickValue != null &&
                        promotionEvent!.clickValue!.isNotEmpty) {
                      launchUrlString(promotionEvent!.clickValue!,
                          mode: LaunchMode.externalApplication);
                    }
                    break;
                  case PromotionEventClickButtonType.inAppRoute:
                    if (promotionEvent!.clickValue != null &&
                        promotionEvent!.clickValue!.isNotEmpty) {
                      context.push(promotionEvent!.clickValue!);
                    }

                    break;
                  case PromotionEventClickButtonType.none:
                }
              },
              child: Row(
                children: [
                  Text(
                    '详情',
                    style: TextStyle(
                      color: stringToColor(
                          promotionEvent!.clickButtonColor ?? 'FFFFFFFF'),
                      fontSize: 14,
                    ),
                  ),
                  const SizedBox(width: 5),
                  Icon(
                    Icons.keyboard_double_arrow_right,
                    size: 16,
                    color: stringToColor(
                        promotionEvent!.clickButtonColor ?? 'FFFFFFFF'),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  /// 构建发送或者语音按钮
  Widget _buildSendOrVoiceButton(
    BuildContext context,
    CustomColors customColors,
  ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          children: [
            InkWell(
              onTap: () {
                HapticFeedbackHelper.mediumImpact();

                openModalBottomSheet(
                  context,
                  (context) {
                    return VoiceRecord(
                      onFinished: (text) {
                        // _textController.text = _textController.text + text;
                        Navigator.pop(context);
                      },
                      onStart: () {},
                    );
                  },
                  isScrollControlled: false,
                  heightFactor: 0.8,
                );
              },
              child: Icon(
                Icons.mic,
                color: customColors.chatInputPanelText,
                size: 28,
              ),
            ),
            const SizedBox(width: 10),
            if (currentModel != null && currentModel!.model.supportVision)
              InkWell(
                onTap: () async {
                  // 上传图片
                  HapticFeedbackHelper.mediumImpact();
                  if (selectedImageFiles.length >= 4) {
                    showSuccessMessage('最多只能上传 4 张图片');
                    return;
                  }

                  FilePickerResult? result =
                      await FilePicker.platform.pickFiles(
                    type: FileType.image,
                    allowMultiple: true,
                  );
                  if (result != null && result.files.isNotEmpty) {
                    final files = selectedImageFiles;
                    files.addAll(
                        result.files.map((e) => FileUpload(file: e)).toList());
                    setState(() {
                      selectedImageFiles =
                          files.sublist(0, files.length > 4 ? 4 : files.length);
                    });
                  }
                },
                child: Icon(
                  Icons.camera_alt,
                  color: customColors.chatInputPanelText,
                  size: 28,
                ),
              ),
          ],
        ),
        //发送
        InkWell(onTap: () {
          // onSubmit(context, _textController.text.trim());
        })
      ],
    );
  }

  /// 构建聊天室窗口
  Widget buildChatComponents(
    CustomColors customColors,
    BuildContext context,
    RoomLoaded room,
  ) {
    return Column(
      children: [
        // 聊天内容窗口
        Expanded(
          child: Stack(
            fit: StackFit.expand,
            children: [
              BlocConsumer<ChatMessageBloc, ChatMessageState>(
                listener: (context, state) {
                  if (state is ChatMessageUpdated) {
                    // _previewPageKey.currentState?.isReadyRecord =
                    //     state.message.isReady;
                    // if (!_previewPageKey
                    //     .currentState!.animationController.isAnimating) {
                    //   _previewPageKey.currentState?.isReady =
                    //       state.message.isReady;
                    //   // _previewPageKey.currentState?.refreshState();
                    // }

                    // 聊天内容窗口滚动到底部
                    if (!state.processing && scrollController.hasClients) {
                      // Timer(Duration(milliseconds: 500),
                      //         () => _controller.jumpTo(_controller.position.maxScrollExtent));
                      // scrollController.jumpTo(scrollController.position.maxScrollExtent);
                      scrollController.animateTo(
                        0,
                        duration: const Duration(milliseconds: 500),
                        curve: Curves.easeOut,
                      );
                    }

                    if (state.processing && enableInput.value) {
                      _previewPageKey.currentState?.currentTextIndex = 0;
                      _previewPageKey.currentState?.recordMessage = state.message;
                      Future.delayed(const Duration(seconds: 1)).then((value) {
                        _previewPageKey.currentState?.animationController.repeat();
                      });
                      // 聊天回复中时，禁止输入框编辑
                      setState(() {
                        enableInput.value = false;
                      });
                    } else if (!state.processing && !enableInput.value) {
                      // 更新免费使用次数
                      context
                          .read<FreeCountBloc>()
                          .add(FreeCountReloadEvent(model: 'chat'));
                      // 弹出评价
                      // inAppReviewEvent();
                      // 聊天回复完成时，取消输入框的禁止编辑状态
                      // setState(() {
                      //   enableInput.value = true;
                      // });
                    }
                  }
                },
                buildWhen: (prv, cur) => cur is ChatMessagesLoaded,
                builder: (context, state) {
                  if (state is ChatMessagesLoaded) {
                    return buildChatPreviewArea(
                      state,
                      room.chatQuestion?.records ?? [],
                      room,
                      customColors,
                      chatPreviewController.selectMode,
                    );
                  }
                  return Center(
                      child: CircularProgressIndicator(
                          color: customColors.themeBlueColor));
                },
              ),
              // if (!enableInput.value)
              //   Positioned(
              //     bottom: 10,
              //     width: MediaQuery.of(context).size.width,
              //     child: Center(
              //       child: StopButton(
              //         label: '停止输出',
              //         onPressed: () {
              //           HapticFeedbackHelper.mediumImpact();
              //           context
              //               .read<ChatMessageBloc>()
              //               .add(ChatMessageStopEvent());
              //         },
              //       ),
              //     ),
              //   ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建聊天内容窗口
  Widget buildChatPreviewArea(
    ChatMessagesLoaded loadedState,
    List<RecordModel> examples,
    RoomLoaded room,
    CustomColors customColors,
    bool selectMode,
  ) {
    final loadedMessages = loadedState.messages as List<Message>;
    if (room.room.initMessage != null &&
        room.room.initMessage != '' &&
        loadedMessages.isEmpty) {
      loadedMessages.add(
        Message(
          Role.receiver,
          room.room.initMessage!,
          type: MessageType.initMessage,
          like: 0,
          collection: 0,
        ),
      );
    }

    final messages = loadedMessages.map((e) {
      if (e.serverId != null && room.room.chatRecords.isNotEmpty) {
        try {
          var match = room.room.chatRecords
              .firstWhere((element) => e.serverId == element.id);
          e.like = match.isLike ?? 0;
          e.collection = match.isCollect ?? 0;
        } catch (e) {}
      }

      final stateMessage =
          room.states[widget.stateManager.getKey(e.roomId ?? 0, e.id ?? 0)] ??
              MessageState();
      return MessageWithState(e, stateMessage);
    }).toList();

    chatPreviewController.setAllMessageIds(messages);

    return ChatPreview(
      // padding: enableInput.value ? null : const EdgeInsets.only(bottom: 35),
      key: _previewPageKey,
      keyIndex: 1,
      messages: messages,
      scrollController: scrollController,
      controller: chatPreviewController,
      audioPlayerController: audioPlayerController,
      stateManager: widget.stateManager,
      robotAvatar: const SizedBox(),
      onDeleteMessage: (id) {
        handleDeleteMessage(context, id, chatHistoryId: chatId);
      },
      onResetContext: () => handleResetContext(context),
      onResentEvent: (message, index) {
        scrollController.animateTo(0,
            duration: const Duration(milliseconds: 500), curve: Curves.easeOut);

        handleSubmit(message.text,
            messagetType: message.type, index: index, isResent: true);
      },
      onSpeakEvent: (message) {
        audioPlayerController.playAudioWithMessageId(message.serverId ?? 0);
      },
      onLikeEvent: (message, index) {
        context.read<ChatMessageBloc>().add(ChatMessageUpdateEvent(message));
      },
      onCollectionEvent: (message, index) {
        context.read<ChatMessageBloc>().add(ChatMessageUpdateEvent(message));
      },
      onReadyAnimedEvent: () {
        // 弹出评价
        inAppReviewEvent();
        setState(() {
          enableInput.value = true;
        });
      },
      questionWidget: Container(
        margin: const EdgeInsets.only(top: 0, left: 15, right: 15, bottom: 0),
        height: 300,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ListView.separated(
                padding: const EdgeInsets.all(0),
                itemCount:
                    (examples.length ?? 0) > 4 ? 4 : (examples.length ?? 0),
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  return Container(
                    padding: const EdgeInsets.only(
                        top: 18, bottom: 18, left: 16, right: 5),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.15),
                      borderRadius: BorderRadius.circular(19.5),
                    ),
                    child: ListTextItem(
                      title: examples[index].name ?? '',
                      titleIsRight: false,
                      onTap: () {
                        handleSubmit(
                          examples[index].name ?? '',
                        );
                      },
                      customColors: customColors,
                    ),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return const SizedBox(height: 10);
                },
              ),
            ),
            Align(
              alignment: Alignment.centerRight,
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    examples.shuffle();
                  });
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  padding: const EdgeInsets.only(top: 7, bottom: 7),
                  width: 90,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset('images/refresh.png'),
                      const SizedBox(width: 11),
                      Text(
                        AppLocale.refresh.getString(context),
                        style: const TextStyle(
                          color: Color(0xFFA5A5A7),
                          fontSize: 13,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 提交新消息
  void handleSubmit(
    String text, {
    messagetType = MessageType.text,
    int? index,
    bool isResent = false,
  }) async {
    if (currentModel != null && currentModel!.model.freeCount != null) {
      if ((AppUtil().touristLoginModel?.isVip ?? 0) == 0 &&
          currentModel!.model.freeCount == '0') {
        _showVipDialog();
        return;
      }
    }

    // 默认true
    enableInput.value = true;
    // ignore: use_build_context_synchronously
    context.read<ChatMessageBloc>().add(
          ChatMessageSendEvent(
            Message(
              Role.sender,
              text,
              user: AppUtil().touristLoginModel?.name ?? '',
              ts: DateTime.now(),
              type: messagetType,
              chatHistoryId: chatId,
              like: 0,
              collection: 0,
            ),
            index: index,
            isResent: isResent,
          ),
        );

    // ignore: use_build_context_synchronously
    context.read<NotifyBloc>().add(NotifyResetEvent());
    // ignore: use_build_context_synchronously
    context
        .read<RoomBloc>()
        .add(RoomLoadEvent(chatHomeRoomId, cascading: false));
  }

  void inAppReviewEvent() async {
    var value = await AppUtil().isAppReview();
    if (!value) {
      final InAppReview inAppReview = InAppReview.instance;

      if (await inAppReview.isAvailable()) {
        inAppReview.requestReview().then((value) {
          print('-------------->requestReview ');
        });
      }
    }
  }

  void _showClearDialog() async {
    audioPlayerController.stop();

    showAnimationDialog(
      context: context,
      transitionType: TransitionType.inFromTop,
      barrierDismissible: true,
      builder: (diaContext) => StatefulBuilder(builder: (diaContext, state) {
        return Dialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            width: 320,
            height: 379,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/duihua_bg.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Center(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 160, bottom: 38),
                    child: MyTextWeight(
                        '创建新对话', 18, Colors.white, FontWeight.w500),
                  ),
                ),
                Padding(
                    padding:
                        const EdgeInsets.only(left: 30, right: 30, bottom: 40),
                    child: MyTextWeight('是否创建新对话窗口，历史聊天记录将清空。', 16,
                        Colors.white, FontWeight.normal)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Button(
                        title: '取消',
                        color: stringToColor('FF666666'),
                        size: const ButtonSize(
                            height: 40, width: 125, fontSize: 16),
                        backgroundColor: stringToColor('FFEEEEEE'),
                        borderRadius: 20,
                        onPressed: () {
                          diaContext.pop();
                        }),
                    const SizedBox(width: 12),
                    Button(
                        title: '确认',
                        color: Colors.white,
                        size: const ButtonSize(
                            height: 40, width: 125, fontSize: 16),
                        backgroundColor: stringToColor('FFEEEEEE'),
                        borderRadius: 20,
                        gradient: const LinearGradient(
                          colors: [
                            Color(0xFF14E0EB),
                            Color(0xFF5988FC),
                          ],
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                        onPressed: () {
                          EasyLoading.show(status: '请稍等...');
                          APIServer().questionClear().then((value) {
                            EasyLoading.dismiss();
                            diaContext.pop();

                            if (value) {
                              context
                                  .read<ChatMessageBloc>()
                                  .add(ChatMessageClearAllEvent());
                              EasyLoading.showSuccess('创建成功');
                            }
                          }).catchError((e) {
                            EasyLoading.dismiss();
                          });
                        }),
                  ],
                )
              ],
            ),
          ),
        );
      }),
    );
  }

  void _showVipDialog() async {
    showAnimationDialog(
      context: context,
      transitionType: TransitionType.inFromTop,
      barrierDismissible: true,
      builder: (diaContext) => StatefulBuilder(builder: (diaContext, state) {
        return Dialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            width: 320,
            height: 380,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/huiyuan_bg.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Row(
                  children: [
                    const Spacer(),
                    IconButton(
                        padding: const EdgeInsets.all(12),
                        onPressed: () {
                          diaContext.pop();
                        },
                        icon: const Icon(Icons.close)),
                  ],
                ),
                Center(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 2, bottom: 20),
                    child: MyTextWeight('免费咨询，无限对话', 14,
                        stringToColor('FF79ACFF'), FontWeight.w400),
                  ),
                ),
                Padding(
                    padding: const EdgeInsets.only(left: 16, right: 16),
                    child: MyTextWeight(
                        'AI模型咨询需要消耗大量算力，我们无法同时支撑大量用户的咨询成本，如果您喜欢本产品，还请开通会员账户来享受免费对话创作权限，感谢您的支持！',
                        14,
                        Colors.white,
                        FontWeight.normal)),
                Padding(
                    padding: const EdgeInsets.only(right: 56, top: 11.5),
                    child: MyTextWeight(
                        '高级会员权限', 14, Colors.white, FontWeight.normal)),
                Padding(
                    padding: const EdgeInsets.only(right: 34, top: 15.5),
                    child: MyTextWeight('无限咨询 ·  高级对话', 14,
                        stringToColor('FF9FD5FF'), FontWeight.normal)),
                Padding(
                    padding: const EdgeInsets.only(right: 34, top: 6),
                    child: MyTextWeight('创作助理 ·  一键原创', 14,
                        stringToColor('FF9FD5FF'), FontWeight.normal)),
                const Spacer(),
                Center(
                  child: Button(
                      title: '确认',
                      color: Colors.white,
                      size: const ButtonSize(
                          height: 42, width: 270, fontSize: 16),
                      backgroundColor: stringToColor('FFEEEEEE'),
                      borderRadius: 20,
                      gradient: const LinearGradient(
                        colors: [
                          Color(0xFF14E0EB),
                          Color(0xFF5988FC),
                        ],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                      ),
                      onPressed: () {
                        diaContext.pop();
                        Future.delayed(const Duration(milliseconds: 400))
                            .then((value) {
                          context.push('/payment');
                        });
                      }),
                ),
                const SizedBox(
                  height: 22,
                ),
              ],
            ),
          ),
        );
      }),
    );
  }
}

class ChatHistoryItem extends StatelessWidget {
  const ChatHistoryItem({
    super.key,
    required this.history,
    required this.customColors,
    required this.onTap,
  });

  final ChatHistory history;
  final CustomColors customColors;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(
        horizontal: 15,
        vertical: 5,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
      ),
      child: Slidable(
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          children: [
            const SizedBox(width: 10),
            SlidableAction(
              label: AppLocale.delete.getString(context),
              borderRadius: BorderRadius.circular(10),
              backgroundColor: Colors.red,
              icon: Icons.delete,
              onPressed: (_) {
                openConfirmDialog(
                  context,
                  AppLocale.confirmDelete.getString(context),
                  () {
                    context
                        .read<ChatChatBloc>()
                        .add(ChatChatDeleteHistory(history.id!));
                  },
                  danger: true,
                );
              },
            ),
          ],
        ),
        child: Material(
          color: customColors.backgroundColor?.withAlpha(200),
          borderRadius: BorderRadius.all(
            Radius.circular(customColors.borderRadius ?? 8),
          ),
          child: InkWell(
            child: ListTile(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              shape: RoundedRectangleBorder(
                borderRadius:
                    BorderRadius.circular(customColors.borderRadius ?? 8),
              ),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      (history.title ?? '未命名').trim(),
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: customColors.weakTextColor,
                        fontSize: 15,
                      ),
                      maxLines: 1,
                    ),
                  ),
                  Text(
                    humanTime(history.updatedAt),
                    style: TextStyle(
                      color: customColors.weakTextColor?.withAlpha(65),
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
              dense: true,
              subtitle: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  (history.lastMessage ?? '暂无内容').trim().replaceAll("\n", " "),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: customColors.weakTextColor?.withAlpha(150),
                    fontSize: 12,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
              onTap: () {
                HapticFeedbackHelper.lightImpact();
                onTap();
              },
            ),
          ),
        ),
      ),
    );
  }
}

void showVipGlobalDialog(BuildContext context) async {
  showAnimationDialog(
    context: context,
    transitionType: TransitionType.inFromTop,
    barrierDismissible: true,
    builder: (diaContext) => StatefulBuilder(builder: (diaContext, state) {
      return Dialog(
        elevation: 0,
        backgroundColor: Colors.transparent,
        child: Container(
          width: 320,
          height: 380,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('images/huiyuan_bg.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Row(
                children: [
                  const Spacer(),
                  IconButton(
                      padding: const EdgeInsets.all(12),
                      onPressed: () {
                        diaContext.pop();
                      },
                      icon: const Icon(Icons.close)),
                ],
              ),
              Center(
                child: Padding(
                  padding: const EdgeInsets.only(top: 2, bottom: 20),
                  child: MyTextWeight('免费咨询，无限对话', 14,
                      stringToColor('FF79ACFF'), FontWeight.w400),
                ),
              ),
              Padding(
                  padding: const EdgeInsets.only(left: 16, right: 16),
                  child: MyTextWeight(
                      'AI模型咨询需要消耗大量算力，我们无法同时支撑大量用户的咨询成本，如果您喜欢本产品，还请开通会员账户来享受免费对话创作权限，感谢您的支持！',
                      14,
                      Colors.white,
                      FontWeight.normal)),
              Padding(
                  padding: const EdgeInsets.only(right: 56, top: 11.5),
                  child: MyTextWeight(
                      '高级会员权限', 14, Colors.white, FontWeight.normal)),
              Padding(
                  padding: const EdgeInsets.only(right: 34, top: 15.5),
                  child: MyTextWeight('无限咨询 ·  高级对话', 14,
                      stringToColor('FF9FD5FF'), FontWeight.normal)),
              Padding(
                  padding: const EdgeInsets.only(right: 34, top: 6),
                  child: MyTextWeight('创作助理 ·  一键原创', 14,
                      stringToColor('FF9FD5FF'), FontWeight.normal)),
              const Spacer(),
              Center(
                child: Button(
                    title: '确认',
                    color: Colors.white,
                    size:
                        const ButtonSize(height: 42, width: 270, fontSize: 16),
                    backgroundColor: stringToColor('FFEEEEEE'),
                    borderRadius: 20,
                    gradient: const LinearGradient(
                      colors: [
                        Color(0xFF14E0EB),
                        Color(0xFF5988FC),
                      ],
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                    ),
                    onPressed: () {
                      diaContext.pop();
                      Future.delayed(const Duration(milliseconds: 400))
                          .then((value) {
                        context.push('/payment');
                      });
                    }),
              ),
              const SizedBox(
                height: 22,
              ),
            ],
          ),
        ),
      );
    }),
  );
}
